package io.github.zhonglunsheng.core.aop;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class TemplateGenAop {

    @Pointcut("execution(* io.github.zhonglunsheng.core.template.TemplateService+.generateTemplate(*,*))")
    public void point() {}

    @Around("point()")
    public Object before(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Map<String, Object> variables = (Map<String, Object>) args[1];
        // 执行python代码拦截
        args[1] =  interceptor(variables);
        return joinPoint.proceed(args);
    }

    private Map<String, Object> interceptor(Map<String, Object> variables) {
        Process proc;
        try {
            // 从全局变量获取python执行脚本路径 和 开关
            Map<String, String> etx = (Map<String, String>) variables.get("etx");
            if (etx == null) {
                log.debug("当前python扩展脚本未设置");
                return variables;
            }
            // 开启python扩展
            if (!Boolean.valueOf(etx.get("status"))) {
                log.debug("当前python扩展脚本状态禁止启用");
                return variables;
            }

            // 写入临时文件
            if (StrUtil.isBlank(etx.get("tempPath"))) {
                log.debug("当前临时文件路径为空");
                return variables;
            }



            Files.write(Paths.get(etx.get("tempPath")), JSONObject.toJSONString(variables).getBytes(StandardCharsets.UTF_8));

            // 执行py文件
            proc = Runtime.getRuntime().exec("python " + etx.get("scriptPath") + " " + JSONObject.toJSONString(variables));
            // 获取编码
            String charset = etx.get("charset") == null ? "utf-8" : etx.get("charset");
            //用输入输出流来截取结果
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), charset));
            String line = null;
            StringBuilder result = new StringBuilder();

            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.debug("获取扩展后的变量信息: {}", result);
            in.close();
            proc.waitFor();
            return JSONObject.parseObject(result.toString(), Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return variables;
    }


    public static void main(String[] args) throws IOException {
        Process proc = Runtime.getRuntime().exec("python D:\\code\\gitee\\online-code-gen\\target\\test.py");
        BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line = null;
        StringBuilder result = new StringBuilder();
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        System.out.println("result = " + result);
    }
}
